﻿using System;
using System.Collections.Generic;


namespace Candy.Web.Model
{
    public class Autonaming
    {
        public static string NameGene(string genotypeName, int geneId)
        {
            if (!string.IsNullOrEmpty(genotypeName))
            {
                return genotypeName + geneId.ToString("0000000");
            }
            else
            {
                return "N/A" + geneId.ToString("0000000");
            }
        }

     

        public static bool NameGenotype(List<string> existingNames, string genus, string species, out string autoName)
        {
            autoName = null;
            int speciesStartindex;
            string newId = genus.Trim().Substring(0, 1).ToUpper();
            if (!string.IsNullOrEmpty(species) && species.Trim() != "sp." && species.Length > 1)
            {
                newId += species.Trim().Substring(0, 1).ToLower();
                speciesStartindex = 1;
            }
            else
            {
                newId += genus.Trim().Substring(1, 1).ToLower();
                speciesStartindex = 0;
            }
            bool idFound = false;

            if (!string.IsNullOrEmpty(species) && species.Trim() != "sp.")
            {
                //Console.WriteLine("a");
                for (int i = speciesStartindex; i < species.Length; i++)
                {

                    newId += species.Trim().Substring(i, 1).ToLower();
                    if (!existingNames.Contains(newId))
                    {
                        idFound = true;
                        break;
                    }
                    newId = newId.Substring(0, 2);
                }
            }
            else
            {
                //                Console.WriteLine("b");
                for (int i = 2; i < genus.Length; i++)
                {

                    newId += genus.Trim().Substring(i, 1).ToLower();
                    if (!genus.Contains(newId))
                    {
                        idFound = true;
                        break;
                    }
                    newId = newId.Substring(0, 2);
                }
            }
            if (idFound)
                autoName = newId;

            return idFound;


        }
    }
}